package ipt.capitulo20;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.geom.*;
public class DibujaFunciones{
	Tablero tablero;
	int figura=0;
	JSlider barraI,barraD,barraA;
	double escala=0.4;
	double origenX=50;
	double origenY=-250;
	JFrame marco;
	DibujaFunciones(){
		JFrame.setDefaultLookAndFeelDecorated(true); 
		marco = new JFrame("Dibuja funciones");
		marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		marco.setLayout(new BorderLayout());
		tablero = new Tablero();
		VigilaCA vigilante = new VigilaCA();
		String figuras[]={"Seno","Coseno"};
		CasillasActivacion cA =new CasillasActivacion(
			"Funciones: ", figuras, 0,vigilante);
		barraD = new JSlider(JSlider.VERTICAL,
			-100, 100, (int)(escala*10));
		barraI = new JSlider(JSlider.VERTICAL,
			-500, 500, (int)origenY);
		barraA = new JSlider(JSlider.HORIZONTAL,
			-500, 500, (int)origenX);
		barraD.addChangeListener(new VigilaCursores());
		barraI.addChangeListener(new VigilaCursores());
		barraA.addChangeListener(new VigilaCursores());
		marco.add(cA,"North"); 
		marco.add(tablero,"Center");
		marco.add(barraI,"West");
		marco.add(barraD,"East");
		marco.add(barraA,"South"); 
		marco.setVisible(true);
		marco.pack();
	}
	class VigilaCA implements ItemListener{
		public void itemStateChanged(ItemEvent e){
			Checkbox cb=(Checkbox)e.getItemSelectable();
			if(cb.getLabel().equals("Seno"))
				figura=1;
			else
				figura=2; 
			tablero.repaint();
		}
	}
	class Tablero extends Canvas{
		AffineTransform transforma;
		Tablero(){
			escalaTablero();
		}
		void escalaTablero(){
			transforma=null;
			transforma=new AffineTransform();
			transforma.scale(escala,-1*escala);
			transforma.translate(origenX,origenY);
			repaint();
		}
		public void paint(Graphics g) {
			Graphics2D g2=(Graphics2D) g;
		g2.setTransform(transforma);
		int aXI=0,aYI=0;
		int xI,yI;
		if(figura==0){
			g2.clearRect(0, 0,1000 ,1000);
			return;
		}
		if(figura==2) aYI=100;
			g2.clearRect(0, 0,1000 ,1000);
			g2.setColor(new Color(0,0,255));
			g2.drawLine(0,0,(int)(2*Math.PI*100),0);
			g2.drawLine(0,200,0,-200);
			g2.setColor(new Color(255,0,0));
			for(double x=0;x<2*Math.PI;x+=0.1){
				xI= (int)(x*100);
				if(figura==1)
					yI= (int)(Math.sin(x)*100); 
				else
					yI= (int)(Math.cos(x)*100);
				g2.drawLine(aXI,aYI,xI,yI);
				aXI=xI; aYI=yI;
			}
		}
	}
	public static void main(String args[]){
		DibujaFunciones v1 =new DibujaFunciones();
	}
	class VigilaCursores implements ChangeListener{
		public void stateChanged(ChangeEvent e){
			escala =(double)barraD.getValue()/10.0;
			origenX =(double)barraA.getValue();
			origenY =(double)barraI.getValue();
			tablero.escalaTablero();
		}
	}
}
